<template>
  <div class="index">

    <div style="margin: 20px;">
      <el-button type="primary" size="small" v-if="$store.getters.button.includes('article:add')" icon="el-icon-circle-plus-outline" @click="$router.push({ name: 'ArticleEdit' })" > 添 加 </el-button>
      <el-button type="danger" size="small" icon="el-icon-refresh" @click="reload" > 刷 新 </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      element-loading-text="Loading"
      border
      fit
      :stripe="true"
      highlight-current-row
      :data="articleList"
      style="width: 100%"
    >
      <el-table-column
        fixed
        prop="id"
        label="ID"
        sortable
        align="center"
        width="170">
      </el-table-column>
      <el-table-column
        prop="title"
        label="标题"
        align="center"
        width="360">
      </el-table-column>
      <el-table-column
        prop="author"
        label="作者"
        align="center"
        width="80">
      </el-table-column>
      <el-table-column
        prop="likes"
        label="点赞"
        align="center"
        sortable
        width="80">
      </el-table-column>
      <el-table-column
        prop="look"
        label="浏览"
        sortable
        align="center"
        width="80">
      </el-table-column>
      <el-table-column
        label="分类"
        sortable
        align="center"
        width="150">
        <template slot-scope="scope">
          <el-tag>
            {{scope.row.category.categoryName.toString()}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column

        label="状态"
        sortable
        align="center"
        width="80">
        <template slot-scope="scope">
          <el-switch
            active-color="#13ce66" inactive-color="#ff4949"
            v-model="scope.row.status" :value="scope.row.status"
            :active-value="1" :inactive-value="0"
            @click.native="updateArticleStatus(scope.$index, scope.row,scope.row.status)"
          >
          </el-switch>
        </template>

      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        sortable
        align="center"
        width="160">
      </el-table-column>

      <el-table-column fixed="right" align="center">

        <template  slot="header" slot-scope="scope"  style="display: inline-block">
          <el-input
            v-model="searchKeyword"
            @keyup.enter.native="searchArticle"

            placeholder="输入关键字搜索 回车搜索"/>
          <el-button  type="danger" size="small" icon="el-icon-delete" v-if="isSearch" @click="cancelSearchArticle">取 消</el-button>
        </template>


        <template slot-scope="scope">
          <el-button

            size="small"
            type="success"
            icon="el-icon-edit"
            v-if="$store.getters.button.includes('article:update')"
            @click="openEditDialog(scope.$index, scope.row)"
            >编 辑</el-button>
          <el-button

            size="small"
            type="danger"
            icon="el-icon-delete"
            v-if="$store.getters.button.includes('article:delete')"
            @click="openDeleteDialog(scope.$index, scope.row)"
            >删 除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!--    分页插件-->
    <div  v-if="isSearch==false" class="block" style="text-align: center; margin-top: 20px">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="pageNum"
        :page-size="pageSize"
        layout="prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!--    分页插件-->
    <div v-if="isSearch==true" class="block" style="text-align: center; margin-top: 20px">
      <el-pagination
        @current-change="handleSearchCurrentChange"
        :current-page.sync="searchPageNum"
        :page-size="searchPageSize"
        layout="prev, pager, next, jumper"
        :total="searchTotal">
      </el-pagination>
    </div>



    <!--    编辑对话框-->
    <el-dialog title="编辑文章" :visible.sync="dialogArticleEditVisible" width="80%" top="0vh" destroy-on-close="true" :close-on-click-modal='false'>


      <ArticleDetail :parentArticle="toChildrenArticleData" :categoryListTree="categoryList" :parentTagsList="tagsList" @updateArticle="updateArticle"></ArticleDetail>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogArticleEditVisible = false">取 消</el-button>
        <el-button type="primary" size="small" icon="el-icon-el-icon-circle-plus-outline" @click="dialogArticleEditVisible = false">确 定</el-button>
      </div>
    </el-dialog>

    <!--    删除对话框-->
    <div class="dialog">
      <el-dialog title="删除标文章" :visible.sync="dialogArticleDeleteVisible" align="center" width="30%" destroy-on-close="true"
                 :close-on-click-modal='false'>
        <span>是否删除 << {{articleInfo.id  + ":" + articleInfo.title }} >> </span>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogArticleDeleteVisible = false">取 消</el-button>
          <el-button  type="danger" size="small" icon="el-icon-delete" @click="deleteArticle">删 除</el-button>
        </div>
      </el-dialog>
    </div>


  </div>

</template>


<script>
  import {getArticleList,deleteArticle,updateArticleStatus,searchArticle} from '@/api/article'
  import {getCategoryList} from '@/api/category'
  import { getTagsList } from '@/api/tags'
  import ArticleDetail from '@/components/ArticleDetail/index.vue'
  import { mapGetters } from 'vuex'
  export default {
    name: 'index',
    inject: ['reload'],
    data() {
      return {
        toChildrenArticleData:null, //将文章内容发送给子组件
        dialogArticleEditVisible: false, //编辑对话框
        dialogArticleDeleteVisible: false, //删除对话框
        listLoading: true,
        articleList: [],
        pageNum:1,    //当前页
        pageSize:10,   //每页条数
        pages:0, //总页数
        total: 0,     //总数据

        searchKeyword: '',
        searchPageNum:1,
        searchPageSize: 10,
        searchPages: 0,
        searchTotal: 0,
        isSearch: false,
        articleInfo:{
          "id":null,
          "title":'',
        },
        categoryList:Array,
        tagsList:Array,

      }
    },
    computed: {
      ...mapGetters([
        'name',
        'roles'
      ])
    },
    mounted: function() {
      this.getArticleList()

      this.getCategoryList()

      this.getTagsList();

    },
    methods: {

      /**
       * 搜索文章
       */
      searchArticle(){

        this.listLoading = true

        // 获取userId

        // 查询条件
        // api获取
        searchArticle(this.searchKeyword,this.searchPageNum-1,this.searchPageSize).then(response => {

          if (response.code == 200) {
            this.isSearch = true
            const { data } = response

            this.articleList = data.content //数据
            this.searchPageNum = parseInt(data.number+1) //当前页
            this.searchPageSize = parseInt(data.size)    //每页条数
            this.searchPages = parseInt(data.totalPages)    //总页数
            this.searchTotal = parseInt(data.totalElements)   //总条数
          }


        }).catch(error => {
          console.log(error);
        })

        this.listLoading = false
      },

      /**
       * 取消搜索
       * */
      cancelSearchArticle(){
        if (this.isSearch == true) {
          this.isSearch = false
          this.getArticleList();
        }
      },


      /**
       * 获取文章列表
       */
      getArticleList(){

        this.listLoading = true

        // 查询条件
        const searchMap = {
          'roles': this.roles,
          'author': this.name
        }
        console.log('searchMap:' + JSON.stringify(searchMap))

        // api获取
        getArticleList(this.pageNum,this.pageSize,searchMap).then(response => {

          if (response.code == 200) {
            const { data } = response


            this.articleList = data.records //数据
            this.pageNum = parseInt(data.current) //当前页
            this.pageSize = parseInt(data.size)    //每页条数
            this.pages = parseInt(data.pages)    //总页数
            this.total = parseInt(data.total)   //总条数
          }


        }).catch(error => {
          console.log(error);
        })

        this.listLoading = false
      },

      /**
       * 打开编辑对话框
       * @param index
       * @param rowData
       */
      openEditDialog(index,rowData){

        // 设置给子组件的数据
        // this.toChildrenArticleData = rowData 对象浅拷贝
        this.toChildrenArticleData=JSON.parse(JSON.stringify(rowData));   //对象深拷贝

        // 打开对话框
        this.dialogArticleEditVisible = true;
      },


      /**
       * 打开删除对话框
       * @param index
       * @param rowData
       */
      openDeleteDialog(index,rowData){

        this.articleInfo=JSON.parse(JSON.stringify(rowData));   //对象深拷贝

        // 打开对话框
        this.dialogArticleDeleteVisible = true;
      },

      /**
       * 删除文章
       */
      deleteArticle(){


        // api获取
        deleteArticle(this.articleInfo.id).then(response => {

          if (response.code == 200) {

            this.$message({
              showClose: true,
              message: response.message,
              type: 'success',
              center: true
            });

            // 删除本地数据
            this.articleList.forEach((articleItem,index) =>{
              if (articleItem.id == this.articleInfo.id){
                // 删除数据
                this.articleList.splice(index,1)
                return
              }
            })

            // 关闭弹窗
            this.dialogArticleDeleteVisible = false;
          }


        }).catch(error => {
          console.log(error);
        })

       },

      /**
       * 修改状态
       */
      updateArticleStatus(index,rowData,status){
        console.log(rowData.id)
        console.log(status)

        // api获取
        updateArticleStatus(rowData.id,{'status':status}).then(response => {

          if (response.code == 200) {
            const { data } = response


            this.$message({
              showClose: true,
              message: data.message,
              type: 'success',
              center: true
            });

          }


        }).catch(error => {
          console.log(error);
        })
       },

      /**
       * 更新数据
       * */
      updateArticle(article){
        this.articleList.forEach((item,index)=>{
          if (item.id === article.id){
            //数组这种设置能更新数据
            this.$set(this.articleList,index,article);
            return
          }

        })
        this.dialogArticleEditVisible = false
      },

      /**
       * 触发其他页
       * @param val
       */
      handleCurrentChange(val) {
        this.pageNum = val
        this.getArticleList();
      },


      /**
       * 搜索分页 触发其他页
       * @param val
       */
      handleSearchCurrentChange(val) {
        this.searchArticle();
      },


      /**
       * 获取分类列表
       */
      getCategoryList() {

        // api获取
        getCategoryList().then(response => {

          if (response.code == 200) {
            const { data } = response
            // 更新数据
            this.categoryList = this.getTreeData(data)
          }

        }).catch(error => {
          console.log(error)
        })
      },

      /**
       * 获取标签列表
       */
      getTagsList() {

        // api获取
        getTagsList().then(response => {

          if (response.code == 200) {
            const { data } = response
            // 更新数据
            this.tagsList = data
          }

        }).catch(error => {
          console.log(error)
        })

      },

      // 递归判断列表，把最后的children设为undefined
      getTreeData(data) {
        for (var i = 0; i < data.length; i++) {
          if (data[i].children === null || data[i].children.length < 1) {
            // children若为空数组，则将children设为undefined
            data[i].children = undefined
          } else {
            // children若不为空数组，则继续 递归调用 本方法
            this.getTreeData(data[i].children)
          }
        }
        return data
      },


    },
    components:{
      ArticleDetail
    }
  }
</script>

<style scoped>
.index{
  margin:10px 20px;
}

</style>
